package main

import (
	"context"
	"fmt"
	"golang.org/x/sync/errgroup"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

type MyServe struct {
	port int
}

func (m *MyServe) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	fmt.Fprint(w, "My port is:"+strconv.Itoa(m.port))
}

var sigs = []os.Signal{syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGABRT}

var servers []*http.Server

func main() {
	g, ctx := errgroup.WithContext(context.Background())
	c := make(chan os.Signal, 1)
	signal.Notify(c, sigs...)
	for i := 18080; i <= 18090; i++ {
		servers = append(
			servers,
			&http.Server{Addr: ":" + strconv.Itoa(i), Handler: &MyServe{port: i}},
		)
	}
	for _, s := range servers {
		t := s
		g.Go(func() error {
			return t.ListenAndServe()
		})
		g.Go(func() error {
			<-ctx.Done()
			return t.Shutdown(context.Background())
		})
	}
	g.Go(func() error {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case sig := <-c:
			return fmt.Errorf("signal of %s", sig.String())
		}
	})
	err := g.Wait()
	if err != nil {
		log.Println(err.Error())
	}
}
